package safeCommitter.core.actions;

import java.lang.reflect.Method;

import org.eclipse.core.resources.IFile;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.ui.IEditorActionDelegate;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IViewPart;

import safeCommitter.core.template.SingleCheckerTemplate;
import safeCommitter.utils.SCUtils;

/**
 * @author Luiz Henrique Rolim
 * 
 *         Entry point for the Run Related Tests Action.
 */
public class SingleCheckerEntry implements IEditorActionDelegate {

	private final SingleCheckerTemplate template = new SingleCheckerTemplate();

	public void run(final IAction action) {
		template.executeTests(action);
	}

	public void selectionChanged(final IAction action,
			final ISelection selection) {
		template.setSelection(selection, action);

	}

	public void init(final IViewPart view) {

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.eclipse.ui.IEditorActionDelegate#setActiveEditor(org.eclipse.jface
	 * .action.IAction, org.eclipse.ui.IEditorPart)
	 */
	public void setActiveEditor(final IAction action,
			final IEditorPart targetEditor) {
		// CRAZY ECLIPSE BUG... Needed to use reflection for getting the file in
		// which the user performed the run related test class.
		if (targetEditor == null)
			return;
		IEditorInput editorInput = targetEditor.getEditorInput();
		Class<?> c = editorInput.getClass();
		try {
			Method method = c.getMethod("getFile");
			IFile file = (IFile) method.invoke(editorInput);
			ICompilationUnit compilationUnit = SCUtils.getJavaElement(file);
			template.setUnit(compilationUnit);
			template.setProject(compilationUnit.getJavaProject());
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}
